<template>
  <!-- 服务分类管理 -->
  <BaseMainSlot :show-tab="true">
    <template v-slot:btn-box>
      <ActionBar
        :has-add="false"
        :has-edit="false"
        :has-del="false"
        :has-save="false"
        :has-cancel="false"
        :has-auto-back="true"
        :has-manual-back="true"
        :has-maintain="true"
        @maintain="maintain"
      />
    </template>
    <!-- <template v-slot:search-box>
      <SearchBox @search="search">
        <div class="common-search-item">
          <div class="label">事件名称:</div>
          <div class="input">
            <el-input v-model="searchForm.eventName" clearable @keyup.enter.native="search" @blur="search" @clear="search" />
          </div>
        </div>
      </SearchBox>
    </template> -->
    <template v-slot:table-box>
      <!-- 业务组件展示表格 -->
      <div class="zh-table-view">
        <el-table
          :data="tableData"
          height="100%"
          @row-click="handleEdit"
        >
          <el-table-column
            type="index"
            width="50"
          />
          <el-table-column
            prop="operateType"
            label="操作类型"
          >
            <template slot-scope="scope">
              {{ getType(scope.row) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="handleName"
            label="操作人"
          />
          <el-table-column
            prop="operateTime"
            label="操作时间记录"
          >
            <template slot-scope="scope">
              {{ dateToFormat(scope.row.operateTime) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="remark"
            label="备注"
          />
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                @click="edit"
              >查看详情</el-button>
              <!-- <el-button
                size="mini"
                type="danger"
                @click="dellineallmes(scope.$index, scope.row)"
              >删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>
        <Pagination
          :page-size="pageSize"
          :current-page="currentPage"
          :total-size="totalSize"
          @changePageSize="changePageSize"
          @changeCurrentPage="changeCurrentPage"
        />
      </div>
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="dialogTitle"
        class="formData"
        :visible.sync="dialogFormVisible"
        width="40%"
        :before-close="() => { cancel() }"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item label="数据库表选择:" class="w100p">
            <el-tree
              ref="tree"
              v-loading="loading"
              class="database"
              :data="dataList"
              show-checkbox
              node-key="label"
              :default-expanded-keys="expandList"
              :default-checked-keys="formData.checkedList"
              :props="defaultProps"
              style="width: 100%;"
            >
            </el-tree>
          </el-form-item>
          <el-form-item v-if="dialogTitle == '自动备份设置'" label="备份规则表达式:" prop="cron" class="w100p">
            <el-input v-model="formData.cron" type="textarea" clearable />
          </el-form-item>
          <template v-if="dialogTitle == '数据异常维护'">
            <el-form-item label="维护方式:" prop="maintain" class="w100p">
              <el-select v-model="formData.maintain" clearable placeholder="请选择">
                <el-option
                  v-for="item in maintainList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="formData.maintain == 1" label="填写SQL语句:" prop="sql" class="w100p">
              <el-input v-model="formData.sql" type="textarea" rows="5" clearable />
            </el-form-item>
            <el-form-item v-if="formData.maintain == 2" label="上传SQL文件:" prop="fileList" class="w100p">
            <el-upload ref="upload" action="" :file-list="formData.fileList" :auto-upload="false" :limit="1"
              :on-change="handleChangeUpload" :on-remove="handleRemove" accept=".sql">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
            </el-form-item>
          </template>
          <el-form-item label="备注:" class="w100p">
            <el-input v-model="formData.remark" clearable />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel()">取 消</el-button>
          <el-button type="primary" @click="save">保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>
<script>
import ActionBar from "@/components/ActionBar/index";
import { mymixin } from "@/utils/mixins";
import SearchBox from "@/components/SearchBox";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot.vue";
import Pagination from "@/components/Pagination";
import Api from "@/api/agricultural-social/data-center/data-backup.js";
import { dateToFormat } from "@/utils/time.js";
import axios from 'axios';
export default {
  components: { ActionBar, BaseMainSlot, Pagination, SearchBox },
  mixins: [mymixin],
  data() {
    return {
      dateToFormat,
      tableData: [],
      pageSize: 10,
      currentPage: 1,
      totalSize: 0,
      formData: {
        checkedList: []
      },
      searchForm: {
        name: ''
      },
      rules: {
        cron: [{ required: true, message: "请输入备份规则表达式", trigger: ["change", "blur"] }],
        maintain: [{ required: true, message: "请选择维护方式", trigger: ["change", "blur"] }],
        sql: [{ required: true, message: "请输入SQL语句", trigger: ["change", "blur"] }],
        fileList: [{ required: true, message: "请上传SQL文件", trigger: ["change", "blur"] }],
      },
      dialogTitle: '',
      maintainList: [
        { label: '填写SQL语句', value: '1' },
        { label: '上传SQL文件', value: '2' },
      ],
      expandList: [],
      checkedList: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      dataList: [],
      loading: false,
    };
  },
  watch: {
  },
  mounted () {
    this.getAllDatabaseAndTable()
    this.gettabledataList()
  },
  methods: {
    getAllDatabaseAndTable () {
      this.loading = true
      Api.getAllDatabaseAndTable().then(res => {
        this.loading = false
        let dataList = []
        res.data.map(el => {
          let arr = el.tableNameList.map(ele => {
            return {
              label: ele,
              databaseName: el.databaseName,
            }
          })
          dataList.push({
            label: el.databaseName,
            children: arr
          })
        })
        this.dataList = dataList
      })
    },
    getType (row) {
      if (row.operateType == 0) {
        return '自动备份'
      }if (row.operateType == 1) {
        return '手动备份'
      }if (row.operateType == 2) {
        return '数据维护'
      } else {
        return ''
      }
    },
    handleRemove (file, fileList) {
      if (!file.raw) {
        this.formData.fileList = this.formData.fileList.filter(item => { return item.url !== file.url })
        this.formData.imgList = this.formData.imgList.filter(item => { return item.imgUrl !== file.url })
      } else {
        this.formData.fileList = fileList
      }
    },
    handleChangeUpload (file, fileList) {
      // this.$refs.upload.clearFiles()
      // const isLt2M = file.size / 1024 / 1024 < 2;
      // if (!isLt2M) {
      //   this.$message.error('上传图片大小不能超过 2MB!');
      //   fileList.pop()
      //   this.formData.fileList = fileList
      // } else {
        this.$set(this.formData, 'fileList', fileList)
        this.$refs.formData.validateField('fileList')
      // }
    },
    // 获取表格信息
    async gettabledataList() {
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        condition: {
          eventName: this.searchForm.eventName || undefined,
        }
      };
      Api.queryPageByCondition(params).then(res => {
        if (res.code == 200) {
          this.tableData = res.data.content || []
          this.totalSize = res.data.totalElements
          this.resetActionBar()
        } else {
          this.$message.warning("获取表格失败")
        }
      })
    },
    handleSelectionChange() {
      this.nowselectedList = [];
      const list = this.$refs.catetreetwo.getCheckedNodes();
      this.nowselectedList = list.map((item) => {
        return item.id;
      });
      if (this.nowselectedList && this.nowselectedList.length > 0) {
        this.delActive = true;
      } else this.delActive = false;
    },
    // 搜索
    search() {
      this.currentPage = 1;
      this.gettabledataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.gettabledataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.gettabledataList();
    },
    maintain (val) {
      this.dialogTitle = val
      this.dialogFormVisible = true
    },
    // 修改
    handleEdit(row) {
      if (row) {
        let area = []
        row.provinceId && area.push(row.provinceId)
        row.cityId && area.push(row.cityId)
        row.areaId && area.push(row.areaId)
        let pictureList = row.businessLicense ? [{ url: 'data:image/jpeg;base64,' + row.businessLicense }] : []
        this.formData = { ...row, area, pictureList };
      }
    },
    // 删除一个业务组件
    dellineallmes(i, e) {
      this.$confirm('此操作将删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        Api.del(e.id).then(res => {
          if (res.code == 200) {
            this.$message.success("删除成功！")
            this.gettabledataList()
          }
        })
      })
    },
    // 保存要添加的业务的组件信息
    save() {
      this.$refs['formData'].validate((valid) => {
        if (valid) {
          let param = {
            ...this.formData,
            handleName: sessionStorage.account,
          }
          let backupDatabaseDTOList = [], databaseAll = [], obj = {}
          const list = this.$refs.tree.getCheckedNodes();
          list.map(el => {
            if (!el.databaseName) {
              backupDatabaseDTOList.push({
                databaseName: el.label,
                flag: true
              })
              databaseAll.push(el.label)
            } else {
              if (!databaseAll.includes(el.databaseName)) {
                if (!obj[el.databaseName]) {
                  obj[el.databaseName] = { databaseName: el.databaseName, flag: false, tableNameList: [] }
                }
                obj[el.databaseName].tableNameList.push(el.label)
              }
            }
          })
          for (let key in obj) {
            backupDatabaseDTOList.push(obj[key])
          }
          if (backupDatabaseDTOList.length == 0) {
            this.$message.warning('请选择数据库和表名')
            return
          }
          param.backupDatabaseDTOList = backupDatabaseDTOList
          let api = ''
          if (['自动备份设置', '手动备份数据'].includes(this.dialogTitle)) {
            api = Api.backupDatabase
          } else if (this.dialogTitle == '数据异常维护') {
            if (this.formData.maintain == 1) {
              api = Api.maintenanceSql
            } else if (this.formData.maintain == 2) {
              api = Api.maintenanceSqlFile
              let data = { ...param }
              delete data.fileList
              let dataForm = new FormData();
              dataForm.append('maintenanceSqlDTO', JSON.stringify(data))
              dataForm.append('file', this.formData.fileList[0].raw)
              param = dataForm
              
              axios({
                method: "POST",
                // url: this.$agrSocialUrl + "/system/databaseBackup/maintenanceSqlFile",
                url: '/api' + "/system/databaseBackup/maintenanceSqlFile",
                data: dataForm,
                headers: {
                  'Content-Type': 'multipart/form-data'
                }
              }).then(
                res => {
                  if (res.data.code == 200) {
                    this.$message.success(res.data.msg || "操作成功！")
                    this.gettabledataList()
                    this.dialogFormVisible = false
                  } else {
                    this.$message.error(res.data.msg)
                  }
                }
              )
              return
            }
          }
          api(param).then(res => {
            if (res.code == 200) {
              this.$message.success(res.msg || "操作成功！")
              this.gettabledataList()
              this.dialogFormVisible = false
            } else {
              this.$message.error(res.msg)
            }
          })
        } else {
          return false;
        }
      });
    },
  }
};
</script>

<style lang="scss" scoped>
  @import "~@/styles/variables.scss";

  .business-main{
  width: 100%;
  height: 100%;
  .topbar-view{
    width: 100%;
    margin-bottom: 5px;
  }
  .zh-table-view{
    width: 100%;
    height: calc(100% - 60px);
    position: relative;
  }
}
.add-components-dia {
  width: 502px;
  // height: 191px;
  background: #303640;
  border: 1px solid #005c6f;
  border-radius: 7px;
  position: fixed;
  top: 15%;
  left: 40%;
  // background-color: #005c6f;
  z-index: 99;
  .top-bar {
    width: 502px;
    height: 10px;
    background: linear-gradient(90deg, #3581fb 0%, #00faad 100%);
    border-radius: 7px 7px 0px 0px;
  }
  .top-title-line {
    width: 490px;
    height: 35px;
    line-height: 35px;
    padding: 6px 8px;
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #484a4e;
    .line-title {
      height: 20px;
      font-size: 14px;
      font-family: PingFang SC-Regular, PingFang SC;
      font-weight: 400;
      color: $textColor;
      letter-spacing: 2px;
    }
    .line-close {
      color: #10d7c4;
      cursor: pointer;
    }
    .line-close:hover {
      color: $textColor;
    }
  }
  .screen-dia-main {
    width: 502px;
    padding: 20px 10px;
    // max-height: 550px;
    overflow-y: auto;
    overflow-x: hidden;
    max-height: 480px;
    .title-config{
      padding-bottom: 20px;
      border-bottom: #00faad 1px solid;
      margin-bottom: 10px;
    }
    .dia-main-inputline {
      width: 482px;
      margin-top: 5px;
      display: flex;
      // justify-content: center;
      align-items: center;
      margin-bottom: 10px;
      .inputline-name {
        width: 120px;
        height: 24px;
        font-size: 16px;
        font-family: PingFang SC-Regular, PingFang SC;
        font-weight: 400;
        color: $textColor;
        line-height: 24px;
        text-align: center;
      }
      .inputline-value {
        width: 350px;
        height: 32px;
        box-sizing: border-box;
        border-radius: 0px 0px 0px 0px;
        opacity: 1;
        border: 1px solid #494e57;
        box-sizing: border-box;
        outline: 0;
      }
      .textarealine-value {
        width: 350px;
        height: 32px;
        box-sizing: border-box;
        border-radius: 0px 0px 0px 0px;
        opacity: 1;
        border: 1px solid #494e57;
        box-sizing: border-box;
        outline: 0;
      }
      .icon-line-value {
        width: 48px;
        height: 48px;
        text-align: center;
        .not-iconurl {
          border: 1px dashed #d9d9d9;
          border-radius: 6px;
          cursor: pointer;
          position: relative;
          overflow: hidden;
        }
        .not-iconurl:hover {
          border-color: #1caf7e;
        }
        .not-iconsty {
          font-size: 20px;
          color: #8c939d;
          width: 48px;
          height: 48px;
          line-height: 48px;
          text-align: center;
        }
      }
      .selcect-one {
        width: 350px;
        height: 32px;
        box-sizing: border-box;
        border-radius: 0px 0px 0px 0px;
        opacity: 1;
        border: 1px solid #494e57;
        box-sizing: border-box;
        outline: 0;
      }
    }
    .dia-main-addline {
      width: 442px;
      font-size: 16px;
      font-family: PingFang SC-Regular, PingFang SC;
      font-weight: 400;
      color: $textColor;
      line-height: 24px;
      border-bottom: #00faad 1px dashed;
      padding-bottom: 16px;
      margin-bottom: 10px;
      .components-line {
        display: flex;
        // justify-content: space-between;
        align-items: center;
        width: 442px;
        height: 48px;
        .slect-name {
          width: 90px;
          height: 36px;
          font-size: 16px;
          font-family: PingFang SC-Regular, PingFang SC;
          font-weight: 400;
          color: $textColor;
          line-height: 36px;
          text-align: center;
        }
        .selcect-one {
          width: 350px;
          color: #00faad;
          margin-top: 12px;
          height: 36px;
          line-height: 36px;
          background-color: transparent;
          border: #00faad dashed 1px;
          cursor: pointer;
          option {
            background-color: #005c6f !important;
            color: $textColor;
            cursor: pointer;
          }
        }
      }
      .addline-but {
        width: 442px;
        display: flex;
        justify-content: space-around;
        margin-top: 15px;
        .addline-but1 {
          color: #00faad;
          border: 1px solid #00faad;
          cursor: pointer;
          padding: 5px 10px;
        }
        .addline-but1:hover {
          color: $textColor;
        }
        .addline-but2 {
          color: #3581fb;
          border: 1px solid #3581fb;
          cursor: pointer;
          padding: 5px 10px;
        }
        .addline-but2:hover {
          color: $textColor;
        }
      }
    }
    .dia-main-addline:last-of-type {
      padding-bottom: 0;
      margin: 0;
      border: none;
    }
    .showkuang-one {
      position: relative;
      left: 41px;
      width: 400px;
      min-height: 200px;
      .kuangone-main {
        position: absolute;
        width: 100%;
        height: 400px;
      }
    }
  }
  .bottom-bar {
    width: 482px;
    height: 50px;
    display: flex;
    justify-content: space-around;
    align-items: center;
    font-size: 16px;
    .bottom-bar-cancel {
      width: 96px;
      height: 33px;
      border-radius: 5px 5px 5px 5px;
      border: 1px solid #0cb9ae;
      color: #0cb9ae;
      cursor: pointer;
      line-height: 33px;
      text-align: center;
    }
    .bottom-bar-cancel:hover {
      color: #00faad;
    }
    .bottom-bar-confirm {
      width: 96px;
      height: 33px;
      background: #0cb9ae;
      border-radius: 5px 5px 5px 5px;
      cursor: pointer;
      line-height: 33px;
      text-align: center;
    }
    .bottom-bar-confirm:hover {
      color: #10fab4;
    }
  }
}
::v-deep .el-switch__label {
  color: #fff !important;

  &.is-active {
    color: #409EFF !important;
  }
}
::v-deep .el-dialog {
  min-width: 35% !important;
}
.search-list {
  .common-search-item {
    .label {
      min-width: 80px !important;
      text-align: right;
    }
  }
}
::v-deep {
  .el-tree-node__label {
    color: #000;
  }
  .el-form-item__label {
    min-width: 150px !important;
  }
  .el-form-item__content {
    text-align: left;
  }
}
.database {
  max-height: 300px;
  overflow: hidden auto;
}
</style>
